package com.douwong.student.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.douwong.student.R;
import com.douwong.student.adapter.MainPagerAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.ClassBaseActivity;
import com.douwong.student.contant.Config;
import com.douwong.student.fragment.HomeFragment;
import com.douwong.student.model.Account;
import com.douwong.student.model.StatusCode;
import com.douwong.student.model.StudentAtt;
import com.douwong.student.model.StudentInfo;
import com.douwong.student.model.StudentOnline;
import com.douwong.student.model.UserBean;
import com.douwong.student.popuwindow.AppVersionUpdate;
import com.douwong.student.rxjava.EndPointInterface;
import com.douwong.student.rxjava.NetWork;
import com.douwong.student.utils.AppInfoUtils;
import com.douwong.student.utils.CheckPermission;
import com.douwong.student.utils.CyptoUtils;
import com.douwong.student.utils.DateTools;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.PreferencesUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.view.CircleTransform;
import com.douwong.student.view.TabPageIndicator;

import java.io.File;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.douwong.student.R.id.indicator;

public class MainActivity extends ClassBaseActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    public static final int LoginQuestCode = 500;
    public static final int LoginResponeCode = 5001;
    public static final int SetPersonInfoQuesCode = 5003;
    public static final int SetPersonInfoResponeCode = 5004;

    public static final int NoticeQuestCode = 5005;  //通知请求码
    public static final int NoticeResponeCode = 5006; //通知响应码
    private TextView mTxUserName, mTextStarNumber, mTextBattery, mTextCurrentLevel, mTextVersionName;
    private ImageView mIvHeadPhoto, mIvSet;
    private ViewPager mPager;
    private FragmentPagerAdapter mAdapter;
    private AppVersionUpdate mAppVersionUpdate;

    //配置需要取的权限
    static final String[] PERMISSION = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
            Manifest.permission.READ_EXTERNAL_STORAGE,  //读取权限
            Manifest.permission.CAMERA,//相机
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,


    };

    private static final int REQUEST_CODE = 2002;//请求码
    private TabPageIndicator mIndicator;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //  super.onSaveInstanceState(outState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_main);
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        Log.d(TAG, "Max memory is " + maxMemory + "KB");
        mTxUserName = (TextView) findViewById(R.id.user_name);
        mTextStarNumber = (TextView) findViewById(R.id.activity_main_textstarnumber);
        mTextBattery = (TextView) findViewById(R.id.battery_text);
        mTextCurrentLevel = (TextView) findViewById(R.id.current_level);
        mTextVersionName = (TextView) findViewById(R.id.tv_versionname);
        mIvHeadPhoto = (ImageView) findViewById(R.id.activity_main_headphoto);
        mIvSet = (ImageView) findViewById(R.id.activity_main_iv_set);
        mIndicator = (TabPageIndicator) findViewById(indicator);

    }

    /**
     * 判断是否是6.0以上
     *
     * @return
     */
    private boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    @Override
    protected void initData() {

        Configuration config = getResources().getConfiguration();
        int smallestScreenWidth = config.smallestScreenWidthDp;
        LogUtils.i("smallest width : ", "" + smallestScreenWidth);
        registerReceiver(mReceiver, mIntentFilter);
        if (!isMarshmallow()) {
            initPerssionData();
            initPerssionEvent();
        } else {
            CheckPermission checkPermission = new CheckPermission(this);
            if (checkPermission.permissionSet(PERMISSION)) {
                startPermissionActivity();
            } else {
                initPerssionData();
                initPerssionEvent();
            }
        }



    }

    //进入权限设置页面
    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, REQUEST_CODE, PERMISSION);
    }


    /**
     * 初始化权限数据
     */
    private void initPerssionData() {
        creatDir();
        mAppVersionUpdate = new AppVersionUpdate(MainActivity.this, mIvHeadPhoto);
        mAppVersionUpdate.checkVersionUpdate(null, true);

        changeLogin();
        mIndicator.setVisibility(View.VISIBLE);
        mAdapter = new MainPagerAdapter(getSupportFragmentManager());
        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setOffscreenPageLimit(4);
        mPager.setAdapter(mAdapter);

        mIndicator.setViewPager(mPager);

        mTextVersionName.setText("v" + AppInfoUtils.getVersionName(this));
        //  int b=10/0;
        //日志上传
      /*  UpLoadDeviceLogTask upLoadDeviceLogTask=new UpLoadDeviceLogTask();
        upLoadDeviceLogTask.execute();*/
    }

    @Override
    protected void initEvent() {
        if (!isMarshmallow()) {

            initPerssionEvent();
        }

    }

    /**
     * 初始化事件
     */
    private void initPerssionEvent() {
        mTxUserName.setOnClickListener(this);
        mIvHeadPhoto.setOnClickListener(this);
        mIvSet.setOnClickListener(this);
    }


    /**
     * 创建目录
     */
    private void creatDir() {
        if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            FileUtils.APP_DIR = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/douwong";
        } else {
            FileUtils.APP_DIR = this.getFilesDir().getAbsolutePath() + "/douwong";
        }
        FileUtils.APP_LOG = FileUtils.APP_DIR + "/log";
        FileUtils.APP_CRASH = FileUtils.APP_DIR + "/crash";
        FileUtils.APK_DIR = FileUtils.APP_DIR + "/apks";
        File appDir = new File(FileUtils.APP_DIR);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        File logDir = new File(FileUtils.APP_LOG);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        File crashDir = new File(FileUtils.APP_CRASH);
        if (!crashDir.exists()) {
            crashDir.mkdirs();
        }
        File apkDir = new File(FileUtils.APK_DIR);
        if (!apkDir.exists()) {
            apkDir.mkdirs();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_name:
            case R.id.activity_main_headphoto:

                if (BaseApplication.sUserBean == null) {
                    //登录
                    logcatI("点击登录");
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivityForResult(intent, LoginQuestCode);

                } else {
                    //个人信息
                    Intent intent = new Intent(this, PersonInfoActivity.class);
                    startActivityForResult(intent, SetPersonInfoQuesCode);
                }

                break;
            case R.id.activity_main_iv_set:
                //设置
                Intent intent = new Intent(this, SetActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 开启登录Activity
     */
    public void startLogingActivityForResult() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, LoginQuestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == LoginQuestCode && resultCode == LoginResponeCode) {
            //获取星星
            ChangeDisplay();
        } else if (requestCode == SetPersonInfoQuesCode && resultCode == SetPersonInfoResponeCode) {
            //修改信息
            changeLogin();
        }
        if (requestCode == REQUEST_CODE) {
            if (resultCode == PermissionActivity.PERMISSION_DENIEG) {
                //没有权限
                finish();
            } else if (resultCode == PermissionActivity.PERMISSION_GRANTED) {
                //有权限
                initPerssionData();
                initPerssionEvent();
            }
        }


    }

    IntentFilter mIntentFilter = new IntentFilter() {
        {
            addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
            addAction(Intent.ACTION_BATTERY_CHANGED);
            addAction(Config.UNREGISTER_LOGIN);
            addAction(Config.LOGIN_SUCCESS);
        }
    };
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        HomeFragment homeFragment;

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                    //网络发送改变
                    if (!NetUtils.NetwrokIsUseful(context)) {
                        //不可用
                        BaseApplication.isLogin = false;
                        if (BaseApplication.sUserBean != null) {
                            mTxUserName.setText("Hi," + BaseApplication.sUserBean.getPersonalbean().getRealName() + "[离线]");
                        } else {
                            mTxUserName.setText("Hi," + "游客" + "[未登录]");
                        }
                    } else {
                        changeLogin();
                    }

                    break;
                case Intent.ACTION_BATTERY_CHANGED:
                    //电池广播
                    int rawlevel = intent.getIntExtra("level", -1);// 获得当前电量
                    // int scale = intent.getIntExtra("scale", -1);
                    int statue = intent.getIntExtra("status", BatteryManager.BATTERY_HEALTH_UNKNOWN);

                    if (statue == BatteryManager.BATTERY_STATUS_CHARGING) {// 充电
                        mTextBattery.setBackgroundResource(R.mipmap.charge_d);
                    } else {
                        mTextCurrentLevel.setVisibility(View.VISIBLE);
                        upDateBattery(rawlevel);
                    }
                    mTextCurrentLevel.setText(rawlevel + "%");

                    break;
                case Config.UNREGISTER_LOGIN:
                    //注销登录
                    mTxUserName.setText("Hi," + "游客" + "[未登录]");
                    mTextStarNumber.setText("0");
                    mIvHeadPhoto.setImageResource(R.mipmap.signin);
                    homeFragment = (HomeFragment) mAdapter.getItem(0);
                    homeFragment.userUnRegisterLogin();
                    break;
                case Config.LOGIN_SUCCESS:
                    //登录成功
                    homeFragment = (HomeFragment) mAdapter.getItem(0);
                    homeFragment.getNoticeList();

                    break;
            }

        }
    };

    /**
     * 更新电池图片
     *
     * @param level
     */
    private void upDateBattery(int level) {
        int battery;
        if (level == 100) {
            battery = R.mipmap.b_100;
        } else if (level >= 90 && level < 100) {
            battery = R.mipmap.b_90;
        } else if (level >= 80 && level < 90) {
            battery = R.mipmap.b_80;
        } else if (level >= 70 && level < 80) {
            battery = R.mipmap.b_70;
        } else if (level >= 60 && level < 70) {
            battery = R.mipmap.b_60;
        } else if (level >= 50 && level < 60) {
            battery = R.mipmap.b_50;
        } else if (level >= 40 && level < 50) {
            battery = R.mipmap.b_40;
        } else if (level >= 30 && level < 40) {
            battery = R.mipmap.b_30;
        } else if (level >= 20 && level < 30) {
            battery = R.mipmap.b_20;
        } else {
            battery = R.mipmap.b_10;
        }
        mTextBattery.setBackgroundResource(battery);
    }

    /**
     * 网络改变成可用时
     */
    public void changeLogin() {
        String name = PreferencesUtils.getInstance().getString(Config.USER_NAME, "");
        String password = PreferencesUtils.getInstance().getString(Config.PASS_WORD, "");
        if (name.equals("") || password.equals("") || !NetUtils.NetwrokIsUseful(this)) {
            return;
        }
        unsubscribe();
        //登录
        subscription = NetWork.getEndPointInterface()
                .login(name, CyptoUtils.MD5(password), "131", NetUtils.getlocalip(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<StatusCode<UserBean>>() {
                    @Override
                    public void call(StatusCode<UserBean> userBeanStatusCode) {
                        if (userBeanStatusCode.isFlag()) {
                            //登录成功
                            BaseApplication.isLogin = true;
                            BaseApplication.sUserBean = userBeanStatusCode.getData();
                            ChangeDisplay();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        ToastUtils.makeText(MainActivity.this, "登录失败");
                    }
                });
    }

    /**
     * 登录成功改变显示
     */
    private void ChangeDisplay() {
        //显示通知

        HomeFragment homeFragment = (HomeFragment) mAdapter.getItem(0);
        homeFragment.getNoticeList();
        unsubscribe();
        NetWork.getEndPointInterface().getStarNumber(BaseApplication.sUserBean
                .getUserbean().getId() + "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<StatusCode<Account>>() {
                    @Override
                    public void call(StatusCode<Account> accountStatusCode) {
                        if (accountStatusCode.isFlag()) {
                            //获取成功
                            PreferencesUtils.getInstance().putString("star", accountStatusCode.getData().getUaStar() + "");
                            mTextStarNumber.setText(accountStatusCode.getData().getUaStar() + "");
                        }
                        logcatI(accountStatusCode.getData().getUaStar() + "");
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        ToastUtils.makeText(MainActivity.this, "获取奖励失败");
                    }
                });

        //显示"Hi," + nickName + "[已登录]"
        if (BaseApplication.sUserBean != null) {
            mTxUserName.setText("Hi" + BaseApplication.sUserBean.getPersonalbean().getRealName() + "[已登录]");
            if (BaseApplication.sUserBean.getPersonalbean().getHeadPortrait() == null || BaseApplication.sUserBean.getPersonalbean().getHeadPortrait().equals("")) {
                mIvHeadPhoto.setImageResource(BaseApplication.sUserBean.getPersonalbean().getSex() == 0 ? R.mipmap.boy_default
                        : R.mipmap.girl_default);
            } else {
                Glide.with(this)
                        .load(EndPointInterface.HEAD_PIC + BaseApplication.sUserBean.getPersonalbean().getHeadPortrait())
                        .placeholder(R.mipmap.signin)
                        .transform(new CircleTransform(this))
                        .into(mIvHeadPhoto);
            }
            createUserDirs();

            // 给在线学生赋值
            StudentOnline studentOnline = new StudentOnline();
            studentOnline.schoolId = BaseApplication.sUserBean.getSchoolId();
            studentOnline.schoolRemark = BaseApplication.sUserBean.getSchoolbean().getRemark();
            studentOnline.gradeId = BaseApplication.sUserBean.getClassbean().getGradeId();
            studentOnline.gradeRemark = BaseApplication.sUserBean.getClassbean().getName();
            studentOnline.classId = BaseApplication.sUserBean.getClassId();
            studentOnline.classRemark = BaseApplication.sUserBean.getClassbean().getName();
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.studentId = BaseApplication.sUserBean.getUserbean().getId();
            studentInfo.studentRemark = BaseApplication.sUserBean.getPersonalbean().getRealName();
            studentOnline.student = studentInfo;
            BaseApplication.sStudentOnline = studentOnline;

            //学生属性
            StudentAtt studentAtt = new StudentAtt(BaseApplication.sUserBean.getPersonalbean().getSex(), BaseApplication.sUserBean.getPersonalbean().getHeadPortrait());
            BaseApplication.sStudentAtt = studentAtt;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        mReceiver = null;
    }

    /**
     * 创建用户目录
     */
    public static void createUserDirs() {
        String userNum = DateTools.getFileNameStr();
        if (BaseApplication.sUserBean != null) {
            userNum = BaseApplication.sUserBean.getUserbean().getEuNumber();
        }

        FileUtils.USERBASEDIR = FileUtils.APP_DIR + File.separator + userNum + File.separator;
        File basFile = new File(FileUtils.USERBASEDIR);

        if (!basFile.exists()) {
            basFile.mkdirs();
        }
        FileUtils.VOICE_DIR = FileUtils.USERBASEDIR + "voice/";
        FileUtils.IMAGE_DIR = FileUtils.USERBASEDIR + "image/";
        FileUtils.FILE_DIR = FileUtils.USERBASEDIR + "file/";
        FileUtils.RESOURCE_DIR = FileUtils.USERBASEDIR + "resource/";

        File imageFile = new File(FileUtils.IMAGE_DIR);
        if (!imageFile.exists()) {
            imageFile.mkdirs();
        }
        File voiceFile = new File(FileUtils.VOICE_DIR);
        if (!voiceFile.exists()) {
            voiceFile.mkdirs();
        }
        File file = new File(FileUtils.FILE_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        File resource = new File(FileUtils.RESOURCE_DIR);
        if (!resource.exists()) {
            resource.mkdirs();
        }
    }

}